package com.oromwin.repos.common;

import java.io.File;
import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.PropertyConfigurator;

public class Logger {
    private static String _configPath = null;
    private static File _file = null;
    private static Properties _properties = null;
    static {
        initiazlie(Common.DEFAULT_PATH);
    }

    private Logger() {
    }

    /**
     * @param configPath
     */
    private static void initiazlie(String configPath) {
        _configPath = configPath;
        _file = new File(_configPath);
        if (_file.exists()) {
            PropertyConfigurator.configure(configPath);
        } else {
            _properties = new Properties();
            _properties.put("log4j.appender.stdout.layout", "org.apache.log4j.PatternLayout");
            _properties.put("log4j.appender.stdout.layout.ConversionPattern", "%m%n");
            _properties.put("log4j.appender.dailyfile.Threshold", "DEBUG");
            _properties.put("log4j.appender.dailyfile", "org.apache.log4j.DailyRollingFileAppender");
            _properties.put("log4j.appender.dailyfile.File", Common.LOGFILE);
            _properties.put("log4j.appender.dailyfile.layout", "org.apache.log4j.PatternLayout");
            _properties.put("log4j.rootLogger", "DEBUG, stdout, dailyfile");
            _properties.put("log4j.appender.stdout", "org.apache.log4j.ConsoleAppender");
            PropertyConfigurator.configure(_properties);
        }
    }

    public static Log getLog(Class clazz) {
        return LogFactory.getLog(clazz);
    }

    public static void errorWithThrowable(Log log, String info) {
        errorWithThrowable(log, null, info);
    }

    public static void errorWithThrowable(Log log, Throwable th, String info) {
        if (log.isDebugEnabled()) th.printStackTrace();

        if (th == null && log.isErrorEnabled()) 
            log.error("[UNKNOWN] " + info);

        Throwable e = th;
        if (e instanceof RuntimeException && e.getCause() != null)
            e = e.getCause();

        StackTraceElement[] ste = e.getStackTrace();
        if (ste != null && ste.length > 0) {
            String temp = "(" + ste[0].getFileName() + ":" + ste[0].getLineNumber() + ") ";
            info = temp + info;
        }

        if (e.getMessage() != null)
            info = "\"" + e.getMessage() + "\" " + info;

        if (log.isErrorEnabled()) log.error("[Exception@" + e.getClass().getName() + "] " + info);
    }
}
